package com.dingup.provider.controller.sys;

import com.dingup.api.Util.DateUtil;
import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.model.sys.SysRole;
import com.dingup.provider.mapper.SysRoleMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.model.sys.Role;
import com.dingup.provider.service.log.RoleUpdateLogService;
import com.dingup.provider.service.sys.SysRoleService;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;

/**
 * Created by wancheng on 2018/7/27.
 */
@RestController()
@RequestMapping("/role")
public class SysRoleController {

    private final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    private final String DEFAULT = "default";

    private final String MYSELF = "myself";

    private final String OTHER = "other";

    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RoleUpdateLogService roleUpdateLogService;


    @RequestMapping(value = "/get_role_except_student.do", method = RequestMethod.POST)
    public void listAllUser(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<Role>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取全部身份(除学生)");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            //获取当前登录人的数据权限(可以查看的员工id)
            List<String> dataPermissionEmployee = RedisUtils.getInstance().getDataPermissionEmployee(userAccount);
            BLogUtil.info("用户id: {}", userId);
            List<SysRole> all = sysRoleService.getByCreateUserId(dataPermissionEmployee);
            //过滤学生身份
            all = all.stream().filter(
                    sysRole -> !"学生".equals(sysRole.getName())
            ).collect(Collectors.toList());
            //每个身份增加类型
            all.stream().forEach(
                            sysRole -> {
                                if (sysRole.getCreateUserId() == null) {
                                    sysRole.setType(DEFAULT);
                                } else if (sysRole.getCreateUserId().equals(userId)) {
                                    sysRole.setType(MYSELF);
                                } else {
                                    sysRole.setType(OTHER);
                                }
                                String dateString = DateUtil.date2Str(sysRole.getCreateTime(), "yyyy-MM-dd");
                                sysRole.setCreateTimeString(dateString);
                            }
                    );
            //转为map
            Map<String, List<SysRole>> res = all.stream().collect(Collectors.groupingBy(SysRole::getType));
            //默认身份时间正序
            Collections.sort(res.get(DEFAULT), new Comparator<SysRole>() {
                @Override
                public int compare(SysRole o1, SysRole o2) {
                    if (o1.getCreateTime().after(o2.getCreateTime())) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });
            List<Role> resRole = new ArrayList<>();
            for (Map.Entry<String, List<SysRole>> e : res.entrySet()) {
                Role role = new Role();
                if (DEFAULT.equals(e.getKey())) {
                    role.setType(DEFAULT);
                    role.setLabel("系统默认");
                    role.setOrder(3);
                } else if (MYSELF.equals(e.getKey())) {
                    role.setType(MYSELF);
                    role.setLabel("我创建的身份");
                    role.setOrder(1);
                } else if (OTHER.equals(e.getKey())) {
                    role.setType(OTHER);
                    role.setLabel("其他人创建的身份");
                    role.setOrder(2);
                }
                role.setRole(e.getValue());
                resRole.add(role);
            }
            Collections.sort(resRole, new Comparator<Role>() {
                @Override
                public int compare(Role o1, Role o2) {
                    return o1.getOrder() - o2.getOrder();
                }
            });
            saveSuccessMsgAndData(hrc, resRole);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_user_roles.do",method = RequestMethod.POST)
    public void getUserRoles(HttpServletRequest request,
                             HttpServletResponse response
    ) {
        HttpResContent<List<SysRole>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取当前登陆用户身份信息");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            List<SysRole> roles = sysRoleService.getByUserId(userId);
            saveSuccessMsgAndData(hrc, roles);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/getUseRoleNum.do",method = RequestMethod.POST)
    public void getUseRoleNum(HttpServletRequest request,
                              HttpServletResponse response,
                              Integer roleId) {
        HttpResContent<Integer> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取当前身份正在使用的人数");
        try {
            Integer num = sysRoleService.getRoleUserNum(roleId);
            saveSuccessMsgAndData(hrc, num);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/role_save.do",method = RequestMethod.POST)
    public void saveRole(HttpServletRequest request,
                         HttpServletResponse response,
                         String roleName) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("增加身份");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            SysRole role = new SysRole();
            role.setCreateUserId(userId);
            role.setCreateTime(new Date());
            role.setName(roleName);
            sysRoleMapper.insertSelective(role);
            //身份修改的日志
            roleUpdateLogService.saveRoleLog(role.getId(), userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/role_update.do",method = RequestMethod.POST)
    public void updateRole(HttpServletRequest request,
                           HttpServletResponse response,
                           Integer roleId, String roleName) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改身份信息");
        try {
            SysRole role = sysRoleMapper.selectByPrimaryKey(roleId);
            role.setName(roleName);
            sysRoleMapper.updateByPrimaryKeySelective(role);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update.do",method = RequestMethod.POST)
    public void update(HttpServletRequest request,
                       HttpServletResponse response,
                       String userId, Integer[] roleIds) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改用户身份");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String uId = RedisUtils.getInstance().getUserId(userAccount);
            sysRoleService.update(userId, roleIds, uId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/copy.do",method = RequestMethod.POST)
    public void copy(HttpServletRequest request,
                     HttpServletResponse response,
                     Integer roleId, String roleName) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("复制身份");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            sysRoleService.copy(roleId, roleName, userId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/delete.do", method = RequestMethod.POST)
    public void delete(HttpServletRequest request,
                       HttpServletResponse response,
                       Integer roleId) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("删除身份");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            SysRole role = sysRoleService.getById(roleId);
            Boolean res = sysRoleService.delete(roleId);
            roleUpdateLogService.deleteRoleLog(roleId, userId, role.getName());
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
